import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { login, logout, refreshToken } from '@/api/login'
import { getInfo } from '@/api/login'
import { getToken, setToken, removeToken, getRefreshToken, setRefreshToken, removeRefreshToken, setCurHospitalId, getCurHospitalId } from '@/utils/auth'
import {pushCallback} from '@/api/push'

const baseUrl = config.baseUrl

const user = {
  state: {
    token: getToken(),
    refreshToken: getRefreshToken(),
    name: storage.get(constant.name),
    staffName: storage.get(constant.staffName),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions),
    companyId: storage.get(constant.companyId),
    hospitalId: storage.get(constant.hospitalId),
    departmentId: storage.get(constant.departmentId),
    oauthId: '',
    staffId: '',
    curHospitalId: getCurHospitalId(),
    iosFirstOpenCamera : storage.get(constant.iosFirstOpenCamera)
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      state.refreshToken = refreshToken
    },
    SET_NAME: (state, name) => {
      state.name = name
      storage.set(constant.name, name)
    },
    SET_STAFFNAME: (state, staffName) => {
      state.staffName = staffName
      storage.set(constant.staffName, staffName)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
      storage.set(constant.avatar, avatar)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
      storage.set(constant.roles, roles)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
      storage.set(constant.permissions, permissions)
    },
    SET_COMPANY_ID: (state, companyId) => {
      state.companyId = companyId
      storage.set(constant.companyId, companyId)
    },
    SET_HOSPITAL_ID: (state, hospitalId) => {
      state.hospitalId = hospitalId
      storage.set(constant.hospitalId, hospitalId)
    },
    SET_DEPARTMENT_ID: (state, departmentId) => {
      state.departmentId = departmentId
      storage.set(constant.departmentId, departmentId)
    },
    SET_OAUTHID: (state, oauthId) => {
      state.oauthId = oauthId
    },
    SET_STAFFID: (state, staffId) => {
      state.staffId = staffId
    },
    SET_CUR_HOSPITAL_ID: (state, hospitalId) => {
      state.curHospitalId = hospitalId
      setCurHospitalId(hospitalId)
    },
    SET_IOS_FIRST_OPEN_CAMERA: (state, iosFirstOpenCamera) => {
      state.iosFirstOpenCamera = iosFirstOpenCamera
      storage.set(constant.iosFirstOpenCamera, iosFirstOpenCamera)
    }
  },

  actions: {
    // 账号密码登录
    pwdLogin({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      return new Promise((resolve, reject) => {
        login({username, password},'password').then(res => {
          const data = res.data
          if (data) {
            setToken(data.token)
            commit('SET_TOKEN', data.token)
            setRefreshToken(data.refreshToken)
            commit('SET_REFRESH_TOKEN', data.refreshToken)
            // #ifdef APP-PLUS
              plus.push.getClientInfoAsync(info => {
                pushCallback({cid: info.clientid})
              })
            // #endif
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 微信快速登录
    wechatLogin({ commit }, code) {
      return new Promise((resolve, reject) => {
        login({code, source: 'wechat_open'},'oauth').then(res => {
          const data = res.data
          if (data) {
            setToken(data.token)
            commit('SET_TOKEN', data.token)
            setRefreshToken(data.refreshToken)
            commit('SET_REFRESH_TOKEN', data.refreshToken)
            // #ifdef APP-PLUS
              plus.push.getClientInfoAsync(info => {
                pushCallback({cid: info.clientid})
              })
            // #endif
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 苹果快速登录
    appleLogin({ commit }, identity) {
      return new Promise((resolve, reject) => {
        login({identity, source: 'apple'},'identity').then(res => {
          const data = res.data
          if (data) {
            setToken(data.token)
            commit('SET_TOKEN', data.token)
            setRefreshToken(data.refreshToken)
            commit('SET_REFRESH_TOKEN', data.refreshToken)
            // #ifdef APP-PLUS
              plus.push.getClientInfoAsync(info => {
                pushCallback({cid: info.clientid})
              })
            // #endif
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 刷新令牌
    RefreshToken({commit, state}) {
      return new Promise((resolve, reject) => {
        if (state.refreshToken) {
          refreshToken(state.refreshToken).then(res => {
            setToken(res.data.token)
            commit('SET_TOKEN', res.data.token)
            setRefreshToken(res.data.refreshToken)
            commit('SET_REFRESH_TOKEN', res.data.refreshToken)
            resolve()
          }).catch(error => {
            reject(error)
          })
        } else {
          reject('refreshToken is not find')
        }
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const data = res.data
          const avatar = (data == null || data.avatar == "" || data.avatar == null) ? require("@/static/images/mine/avatar.png") : data.avatar
          const username = (data == null || data.userName == "" || data.userName == null) ? "" : data.userName
          const staffName = (data == null || data.staffName == "" || data.staffName == null) ? "" : data.staffName
          const staffId = (data == null || data.staffId == "" || data.staffId == null) ? "" : data.staffId
          const companyId = (data == null || data.companyId == "" || data.companyId == null) ? "" : data.companyId
          const hospitalId = (data == null || data.hospitalId == "" || data.hospitalId == null) ? "" : data.hospitalId
          const departmentId = (data == null || data.departmentId == "" || data.departmentId == null) ? "" : data.departmentId
          const iosFirstOpenCamera = (data == null || data.iosFirstOpenCamera == "" || data.iosFirstOpenCamera == null) ? true : data.iosFirstOpenCamera
          if (data.roles && data.roles.length > 0) {
            commit('SET_ROLES', data.roles)
            commit('SET_PERMISSIONS', data.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_STAFFID', staffId)
          commit('SET_NAME', username)
          commit('SET_AVATAR', avatar)
          commit('SET_STAFFNAME', staffName)
          commit('SET_COMPANY_ID', companyId)
          commit('SET_HOSPITAL_ID', hospitalId)
          commit('SET_DEPARTMENT_ID', departmentId)
          commit('SET_CUR_HOSPITAL_ID', hospitalId)
          commit('SET_IOS_FIRST_OPEN_CAMERA', iosFirstOpenCamera)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    setOauthId({commit},oauthId){
      return new Promise((resolve, reject) => {
        commit('SET_OAUTHID', oauthId)
        resolve()
      })
    },
    ReplaceCurHospitalId({commit},hospitalId){
      return new Promise((resolve, reject) => {
        commit('SET_CUR_HOSPITAL_ID', hospitalId)
        resolve()
      })
    },
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_REFRESH_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_NAME', '')
          commit('SET_STAFFNAME', '')
          commit('SET_AVATAR', '')
          commit('SET_COMPANY_ID', '')
          commit('SET_HOSPITAL_ID', '')
          commit('SET_DEPARTMENT_ID', '')
          commit('SET_OAUTHID', '')
          commit('SET_STAFFID', '')
          commit('SET_CUR_HOSPITAL_ID', '')
          removeToken()
          removeRefreshToken()
          storage.clean()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
